<script setup>
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { getClassList } from '@/api/manager.js';
import AddClass from '@/components/AddClass.vue';
import { ElMessage } from 'element-plus';
import { useChangeTab } from '@/utils/routerUtils.js';

const router = useRouter();
const activeTab = ref('');
const { changeTab } = useChangeTab(activeTab);

const value = ref(''); // 讲师
const value1 = ref(''); // 上课时间
const options = [
  { value: '艾伦', label: '艾伦' },
  { value: '大壮', label: '大壮' },
];
const options1 = [
  { value: '周一', label: '周一' },
  { value: '周二', label: '周二' },
];

const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const showAddDialog = ref(false);
const loading = ref(false); // 新增加载状态

const openAddDialog = () => {
  showAddDialog.value = true;
};

const handleClick = (row) => {
  console.log('点击的行数据:', row);
  console.log('classId:', row.classId);
  if (!row.classId || isNaN(row.classId)) {
    console.error('classId 未定义或无效:', row);
    ElMessage.error('无效的班级 ID，无法跳转');
    return;
  }
  const targetPath = `/educational/classManagement/classDetails/${row.classId}`;
  try {
    changeTab(targetPath);
  } catch (error) {
    console.error('跳转失败:', error);
    ElMessage.error('跳转失败，请检查路由配置');
  }
};

async function fetchData() {
  loading.value = true;
  try {
    const params = {
      teacher: value.value || undefined,
      classTime: value1.value || undefined,
    };
    console.log('查询参数:', { current: currentPage.value, size: pageSize.value, ...params });
    const res = await getClassList(currentPage.value, pageSize.value, params);
    console.log('班级列表响应:', res);

    if (!res || !res.detail) {
      throw new Error('API 响应格式错误: detail 缺失');
    }
    if (res.code !== 200) {
      throw new Error(res.message || '获取班级列表失败');
    }

    tableData.value = Array.isArray(res.detail.records)
        ? res.detail.records.map(item => ({
          ...item,
          classId: Number(item.classId || 0),
        }))
        : [];
    total.value = Number(res.detail.total) || 0;

    console.log('班级列表数据:', tableData.value);
    console.log('总记录数:', total.value);
  } catch (error) {
    console.error('获取班级列表失败:', error);
    ElMessage.error('获取班级列表失败，请稍后重试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchData();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  fetchData();
};

onMounted(() => {
  console.log('组件挂载，开始获取班级列表');
  fetchData();
});
</script>

<template>
  <div class="container">
    <div class="top">
      <div class="flex flex-wrap gap-4 items-center">
        <el-select
            v-model="value"
            placeholder="讲师"
            size="large"
            style="width: 240px"
            clearable
        >
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-select
            v-model="value1"
            placeholder="上课时间"
            size="large"
            style="width: 240px"
            clearable
        >
          <el-option
              v-for="item in options1"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <el-button type="primary" size="large" @click="handleSearch" :loading="loading">
          搜索
        </el-button>
        <el-button type="primary" size="large" @click="openAddDialog">
          新增班级
        </el-button>
      </div>
    </div>
    <div class="main">
      <el-table
          :data="tableData"
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column fixed prop="className" label="班级名称" width="200"/>
        <el-table-column prop="courseName" label="课程名称" width="200"/>
        <el-table-column prop="teacher" label="讲师" width="200"/>
        <el-table-column prop="startTime" label="开班日期" width="200"/>
        <el-table-column prop="endTime" label="结班日期" width="200"/>
        <el-table-column fixed="right" label="操作" min-width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleClick(row)">
              详情
            </el-button>
            <el-button link type="primary" size="small">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          layout="prev, pager, next, sizes"
          :current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
          class="page"
      />
    </div>
    <add-class v-model:visible="showAddDialog"/>
  </div>
</template>

<style scoped>
@import 'https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css';

.main {
  padding-top: 20px;
}

.page {
  display: flex;
  justify-content: flex-end;
}
</style>